import {
  SET_LAT,
  SET_LON,
  SET_LOAD_LOCATION,
  SET_EDIT_ADDRESS,
  SET_DEFAULT_ADDRESS,
  SET_CURRENT_ADDRESS
} from '../types'

import { getDefaultAddress, getAddress } from '@/api/address'

export default {
  state: {
    latitude: '25.038479',
    longitude: '102.720089',
    loadLocation: false,
    editAddress: false,
    defaultAddress: null,
    currentAddress: null,
  },
  mutations: {
    [SET_LAT](state, latitude) {
      state.latitude = latitude;
    },
    [SET_LON](state, longitude) {
      state.longitude = longitude;
    },
    [SET_LOAD_LOCATION](state, loadLocation) {
      state.loadLocation = loadLocation;
    },
    [SET_EDIT_ADDRESS](state, editAddress) {
      state.editAddress = editAddress;
    },
    [SET_DEFAULT_ADDRESS](state, defaultAddress) {
      state.defaultAddress = defaultAddress;
    },
    [SET_CURRENT_ADDRESS](state, currentAddress) {
      state.currentAddress = currentAddress;
    },
  },
  actions: {
    async getAddress({ commit }) {
      const { data, code } = await getDefaultAddress()
      if (code !== 200) return
      commit('SET_DEFAULT_ADDRESS', data)
      if (data) commit('SET_CURRENT_ADDRESS', data)
    },
    getLocation({ commit, getters }) {
      commit('SET_LOAD_LOCATION', true)
      uni.getLocation({
        type: 'gcj02',
        success: async ({ latitude, longitude }) => {
          commit('SET_LAT', latitude)
          commit('SET_LON', longitude)
          const { data, code } = await getAddress({
            latitude,
            longitude
          })
          commit('SET_LOAD_LOCATION', false)
          if (code !== 200) return
          if (!getters.currentAddress) {
            commit('SET_CURRENT_ADDRESS', {
              streetCommunity: data.detail,
              latitude,
              longitude
            })
          }
        },
        fail: (err) => {
          console.error('获取位置失败：', err)
          commit('SET_LOAD_LOCATION', false)
        },
      });
    }
  }
};